package com.shigen.demo.config;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.shigen.demo.entity.Result;
import java.util.stream.Collectors;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class WebExceptionHandler extends RuntimeException {

  /**
   * requestBody 实体类形式接受参数验证
   **/
  @ExceptionHandler(MethodArgumentNotValidException.class)
  @ResponseBody
  public Result<String> validationErrorHandler(MethodArgumentNotValidException ex) {
    String message = ex.getBindingResult().getAllErrors().stream()
        .map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
    return Result.err(message);
  }

  /**
   * 统一处理请求参数校验(实体对象传参)
   **/
  @ExceptionHandler(ValidationException.class)
  @ResponseBody
  public Result<String> validationErrorHandler(BindException ex) {
    String message = ex.getBindingResult().getAllErrors().stream()
        .map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
    log.error(message);
    return Result.err(message);
  }

  /**
   * RequestParam 接受参数验证
   **/
  @ExceptionHandler(ConstraintViolationException.class)
  @ResponseBody
  public Result<String> validationErrorHandler(ConstraintViolationException ex) {
    String message = ex.getConstraintViolations().stream().map(ConstraintViolation::getMessage)
        .collect(Collectors.joining());
    return Result.err(message);
  }

  /**
   * 默认异常处理，前面未处理
   **/
  @ExceptionHandler(Exception.class)
  public Result defaultHandler(Exception e) {
    log.error("exception: {}", ExceptionUtil.stacktraceToString(e));
    return Result.err("服务器错误");
  }
}
